<template>
  <!--    <div id="app">-->
  <div id="note" :style="note">
    <div type="center" class="row-bg">


      <el-row style="margin-top:100px">
        <!--        <el-col :span="11">-->
        <el-col :span="13">
          <!--        <div class="grid-content bg-purple">-->
          <h1>欢迎登陆MBTI人格测试系统</h1>
          <el-image :src="require('@/image/flower.jpg')" style="height: 400px; width: 660px"></el-image>
          <p></p>
          <!--        </div>-->
        </el-col>

        <el-col :span="1">
          <div>
            <el-divider class="el-divider--vertical"></el-divider>
          </div>
        </el-col>


        <el-col :span="7">
          <div class="grid-content bg-purple" style="position: center; padding-top: 150px">
            <el-form :model="User" :rules="rules" ref="User" label-width="80px" class="demo-User">
              <el-form-item label="学号" prop="UserId" style="width: 380px">
                <el-input v-model="User.UserId"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="Password" style="width: 380px">
                <el-input v-model="User.Password"></el-input>
              </el-form-item>
            </el-form>

            <el-col :span="13">
              <!--          <el-button-group>-->
              <el-button type="success" @click="submitForm('User')" :round="true">登录</el-button>
              <!--                <el-button type="info" @click="Register('User')">注册</el-button>-->

              <!--            <el-button type="success" @click="Register()" :round="true" style="margin-left:30px;">注册</el-button>-->
              <el-button type="success" @click="showDialog" :round="true" style="margin-left:50px;">注册</el-button>
              <!--          </el-button-group>-->
            </el-col>

          </div>
        </el-col>
      </el-row>

    </div>
    <div>


      <el-dialog @close="closeDialog" append-to-body v-model="dialog" title="注册学生" width="30%" style="top: 150px">
        <el-form :model="NewUser" :rules="Newrules" ref="NewUser">
          <el-row>
            <el-col :span="13">
              <el-form-item label="学号" prop="UserId" style="width: 270px">
                <el-input v-model="NewUser.UserId"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="姓名" prop="sname" style="width: 270px">
                <el-input v-model="NewUser.sname"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="性别" prop="ssex" style="width: 270px">
                <!--                <el-input v-model="NewUser.ssex"></el-input>-->
                <el-select v-model="NewUser.ssex" placeholder="请输入性别" size="mini" prefix-icon="el-icon-edit">
                  <el-option v-for="item in sexname" :value="item">

                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row>
            <el-col :span="13">
              <el-form-item label="年级" prop="grade" style="width: 270px">
                <!--                <el-input v-model="NewUser.grade"></el-input>-->
                <el-select v-model="NewUser.grade" placeholder="请输入年级" size="mini" prefix-icon="el-icon-edit">
                  <el-option v-for="item in gradename" :value="item">

                  </el-option>

                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="13">
              <el-form-item label="学院" prop="class_name" style="width: 270px" >
                <el-select @change="changeEditSelect" v-model="NewUser.college_name" placeholder="请输入学院名称" size="mini" prefix-icon="el-icon-edit">
                  <el-option v-for="(item,index) in department_names"
                             :key="index"
                             :label="item"
                             :value="item">

                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="13">
              <el-form-item label="专业" prop="post_name" style="width: 270px">
                <el-select @change="changeClass" v-model="NewUser.major_name" placeholder="请输入专业名称" size="mini" prefix-icon="el-icon-edit">
                  <el-option
                      v-for="(item, index) in post_type_options"
                      :key="index"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="13">
              <el-col :span="13">
                <el-form-item label="班级" prop="class_name" style="width: 270px">
                  <el-input v-model="NewUser.class_name"></el-input>
                </el-form-item>
              </el-col>
            </el-col>

          </el-row>


          <el-row>
            <!--            <el-col :span="12">-->
            <!--              <el-form-item label="学院表单" prop="class_name" style="width: 200px">-->
            <!--                <el-select @change="changeEditSelect" v-model="NewUser.college_name" placeholder="请输入学院名称" size="mini">-->
            <!--                  <el-option v-for="(item,index) in department_names" :key="index" :label="item" :value="item">-->

            <!--                  </el-option>-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->


            <el-col :span="13">
              <el-form-item label="密码" prop="Password" style="width: 270px">
                <el-input v-model="NewUser.Password"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-button type="success" @click="Register('NewUser')">注册</el-button>
          <el-button @click="dialog=false">取 消</el-button>
        </el-form>
      </el-dialog>
    </div>


  </div>
<!--  requestStudent.SID-->



</template>

<script>
import { ElMessageBox } from 'element-plus'
import Index from '../views/Index.vue'

export default {
  name: "Login",
  components:[
      Index
  ],
  data() {

    return {
      // note: {
      //   backgroundImage:
      // }

      verifyUrl: 'http://localhost:8081' + '/verify/getCode?timestamp=' + new Date().getTime(),
      User: {
        UserId: '',
        Password: '',
        // verify: '',
        // token: '',
      },
      note: {
        backgroundImage: "url(" + require("../image/login.png") + ")",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "auto",
        // backgroundSize: "100% 100%",
        backgroundSize: "100%",
        height: "100%",
        width: "100%",
        position: "fixed",
      },

      NewUser:{
        UserId:'',
        sname:'',
        ssex:'',
        Password:'',
        grade:'',
        college_name:'',
        major_name:'',
        class_name: ''
      },

      rules: {
        UserId:
            { required: true, message: '请输入学号', trigger: 'blur' },

        Password:
            { required: true, message: '请输入密码', trigger: 'blur' },

        // verify: [
        //   { required: true, message: '请输入验证码', trigger: 'blur' },
        // ],
      },

      Newrules:{
        UserId:{required:true,message:'请输入学号',trigger:'blur'},
        sname: {required:true,message:'请输入姓名',trigger:'blur'},
        ssex: {required:true,message:'请输入性别',trigger:'blur'},
        grade: {required:true,message:'请输入年级',trigger:'blur'},
        college_name: {required:true,message:'请输入学院',trigger:'blur'},
        major_name: {required:true,message:'请输入专业',trigger:'blur'},
        Password:{required:true,message:'请输入密码',trigger:'blur'},
        class_name:{required:true,message:'请输入班级',trigger:'blur'}
      },

      sexname:['男','女'],

      gradename:['2018','2019','2020','2021'],

      department_names : ['计算机科学与工程', '机电工程', '文法学院', '生命科学', '理学院','经济管理','信息与通信工程','外国语','土木工程','建筑','设计','国际商','环境与资源','预科教育','物理与材料工程'],
      post_names : {
        '计算机科学与工程' : ['软件工程', '网络工程', '计算机科学与技术', '人工智能'],
        '机电工程' : ['自动化', '测控技术与仪器','车辆工程','机器人工程','机械设计制造及其自动化','智能制造工程'],
        '文法学院' : ['新闻学', '法学','汉语国际教育','汉语言文学'],
        '生命科学' : ['制药工程', '应用化学','生物工程','化学工程与工艺','食品质量与安全','食品科学与工程'],
        '理学院' : ['信息与计算科学', '统计学','区块链工程','数学与应用数学'],
        '经济管理' : ['行政管理', '市场营销','人力资源管理','工商管理','航空服务艺术与管理','经济学','旅游管理'],
        '信息与通信工程' : ['物联网工程', '通信工程','电子信息工程'],
        '外国语' : ['英语', '朝鲜语','日语'],
        '土木工程' : ['土木工程', '工程管理','建筑环境与能源应用工程'],
        '建筑' : ['环境设计', '建筑学','城乡规划'],
        '设计' : ['产品设计', '视觉传达设计','动画','工业设计'],
        '国际商' : ['财务管理', '国际经济与贸易','国际商务','会计学'],
        '环境与资源' : ['生物技术', '环境工程','环境科学'],
        '预科教育' : ['少数民族预科'],
        '物理与材料工程' : ['功能材料', '光电信息科学与工程'],
      },

      class_name:{
        '软件工程' : ['软件201','软件202'],
        '机电工程' : ['机电201','机电202'],
      },

      post_type_options : [],
      class_names :[],

      dialog:false,
      captchaImg: null,
      dialogVisible:false
    };



  },
  created() {
    // this.getCaptcha();
    console.log("登陆页面")
    this.$axios.post("api/logout").then(res => {
      localStorage.clear();
      sessionStorage.clear();
      this.$store.commit("resetState");
      this.$router.push("/login");
    })
  },



  methods: {

    //登录
    submitForm(formName) {

      // localStorage.clear();
      // sessionStorage.clear();

      console.log("formname = ",formName)
      // this.$refs[formName].validate((valid) => {
      //   console.log("valid = ", valid)
      //   if (valid) {
      //     let param = this.$qs.stringify(this.User);
      let param = {...this.User};

      console.log("param = ", param);
      // localStorage.setItem("User", JSON.stringify(formName.data));
      this.$axios.post('api/login', param).then((res) => {
        console.log("res = ", res);

        localStorage.setItem("User", res.data.data);
        sessionStorage.setItem("User", res.data.data);

        if(res.data.msg=="登陆成功"){
          console.log("进入");
          // alert('登陆成功')
          const jwt = res.headers['Authorization']
          this.$router.push({path:'/Index',query:{}}).catch(err => err);
          // this.$router.push('/index')
          this.$store.commit('SET_TOKEN',jwt)
        }
        else if (res.data.msg == "用户不存在"){
          // alert("用户不存在")
        }
        else if (res.data.msg == "学号不能为空"){

        }
        else if (res.data.msg == "密码错误"){
          // alert("密码错误")
        }
        // this.$router.push({path:'/cardtest',query:{}}).catch(err => err);


        else{
          // alert('登陆失败');
        }

      })

      localStorage.setItem("User2", JSON.stringify(this.User));
      // sessionStorage.setItem("User2", JSON.stringify(this.User));

    },

    //注册
    Register(formName) {//注册
      console.log("formname = ",formName)
      this.$refs[formName].validate((valid) =>{
        if(valid){
          console.log(this.NewUser)
          // params里，UserId，sname等变量，是作为json键值对的key，与后端结构的json相对应
          const params = {
            UserId: this.NewUser.UserId,
            sname: this.NewUser.sname,
            ssex: this.NewUser.ssex,
            Password: this.NewUser.Password,
            grade: this.NewUser.grade,
            college_name: this.NewUser.college_name,
            major_name: this.NewUser.major_name,
            class_name: this.NewUser.class_name
          };

          console.log("输入数据："+params.sid+params.sname+params.major_name);

          this.$axios.post('api/Register',{...params}).then(res => {
                console.log(res);

                if(res.data.msg == "注册成功"){
                  // alert("注册成功")
                  const jwt = res.headers['Authorization']
                  this.dialog = false;
                  this.$router.push('/login')
                  this.$store.commit('SET_TOKEN',jwt)
                }

                else{
                  // alert(res.data.msg)
                }

              }
          )

        }
      })


    },

    showDialog() {
      this.dialog = true;
    },
    closeDialog() {
      this.dialog = false;
    },

    changeEditSelect() {
      // 清空专业内容
      this.NewUser.major_name = ''
      // this.NewUser.class_name = ''
      // 遍历专业的下拉选项数组
      for (const k in this.department_names) {
        // 专业名称 是否等于 专业名称的下拉选择数组中的某一项
        if (this.NewUser.college_name === this.department_names[k]) {
          this.post_type_options = this.post_names[this.NewUser.college_name]
        }
      }
        //班级名称是否等于班级名称下拉数组的某一项
      // for(const j in this.post_names){
      //   if(this.NewUser.major_name === this.post_names[j]){
      //     this.class_names = this.class_name[this.NewUser.major_name]
      //   }
      //
      // }
      console.log("post_type_options = "+this.post_type_options);
    },

      changeClass() {
        this.NewUser.class_name = ''

        //班级名称是否等于班级名称下拉数组的某一项
        for (const j in this.post_names) {
          if (this.NewUser.major_name === this.post_names[j]) {
            this.class_names = this.class_name[this.NewUser.major_name]
          }
        }
        console.log(this.NewUser.class_name)
      },

    getCaptcha() {
      this.$axios.get('api/captcha').then(res => {
        console.log('/captcha');
        console.log(res);
        this.User.token = res.data.data.token;
        this.captchaImg = res.data.data.captchaImg;
      })
    }
    //Result : code、msg、data
  }
}
</script>

<style scoped>
/*.el-divider {*/
/*  height: 200px;*/
/*}*/
#el-row {
  background: #e5e8d1;
  /*background:url("../image/ice.jpg");*/
  height: 100vh;
  /*opacity: 0.40;*/
  display: flex;
  align-items: center;
  text-align: center;
}
.captchaImg {
  float: left;
  margin-left: 8px;
  border-radius: 4px;
}
.el-divider--vertical{
  display:inline-block;
  width:1px;
  height:25em;
  margin-top: 90px;
}


/*#app {*/
/*  font-family: 'Avenir', Helvetica, Arial, sans-serif;*/
/*  -webkit-font-smoothing: antialiased;*/
/*  -moz-osx-font-smoothing: grayscale;*/
/*  text-align: center;*/
/*  margin-top: 0px;*/
/*}*/

</style>